<!-- eslint-disable vue/html-self-closing -->
<template>
  <div>
    <el-upload
      action
      :on-change="uploadChange"
      :file-list="fileList"
      list-type="picture-card"
      :http-request="upload"
      :on-preview="lookBigImg"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :limit="limit"
      :class="{exceed: limit === fileList.length}"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <!-- 大图 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
// 引入插件
var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDCED4lDTXO7mKD2g9ScYJrF4jEZgaLvMg',
  SecretKey: 'wlT3SbIvXzKYeW8d1JWYQkz3vgbpokdT'
})
export default {
  name: 'Upload',
  components: {},
  props: {
    staffPhoto: {
      type: null,
      required: true
    }
  },
  data() {
    return {
      file: null,
      staff: null,
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      limit: 1
    }
  },
  computed: {},
  watch: {
    staffPhoto(newVAl, oldVal) {
      if (!newVAl) return
      this.fileList.push({ url: this.staffPhoto })
    }
  },
  created() {

  },
  mounted() {},
  methods: {

    // 放大镜
    lookBigImg(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP  格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 手动上传的函数
    upload(file) {
      const upload_img = this.fileList.find(item => item.uid === file.file.uid)
      upload_img.status = 'uploading'
      upload_img.percentage = 0

      this.staff = URL.createObjectURL(file.file)
      this.file = file

      const index = upload_img.name.lastIndexOf('.')
      const ext = upload_img.name.slice(index)
      cos.uploadFile({
        Bucket: 'sjz-hr-1317544063', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: String(Date.now()) + (Number.parseInt(Math.random() * 10000000)) + (Number.parseInt(Math.random() * 10000000)) + ext, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: upload_img.raw, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function(progressData) {
          upload_img.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
          console.dir(err)
          upload_img.status = 'fail'
        } else {
          console.log('上传成功')
          this.$emit('uploadSuccess', data.Location)
          upload_img.status = 'success'
        }
      })
    },
    uploadChange(file, fileList) {
      this.fileList = fileList
      console.log(this.fileList)
    },
    // 删除事件
    handleRemove(file) {
      this.$emit('uploadSuccess', '')
      this.fileList = []
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .exceed {
    .el-upload--picture-card {
      display: none !important;
    }
  }
}
</style>
